package com.llkj.contractmanagement.contractmanagement.actor;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.llkj.contractmanagement.main.BaseFragment;
import com.llkj.contractmanagement.R;
import com.llkj.contractmanagement.contractmanagement.adapter.ActorAdapter;
import com.llkj.contractmanagement.customview.SideBar;
import com.llkj.contractmanagement.customview.TitleBar;
import com.llkj.contractmanagement.http.HttpMethod;
import com.llkj.contractmanagement.http.UrlConfig;
import com.llkj.contractmanagement.model.ActorBean;
import com.llkj.contractmanagement.model.UserInfoBean;
import com.llkj.contractmanagement.utils.CharacterParser;
import com.llkj.contractmanagement.utils.GsonUtil;
import com.llkj.contractmanagement.utils.PinyinComparator2;
import com.llkj.contractmanagement.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;

/**
 * author: dong.yj
 * created on: 2016/8/15 9:15
 * description:艺人界面
 */
public class ActorFragment extends BaseFragment implements SideBar.OnTouchingLetterChangedListener, View.OnClickListener, AdapterView.OnItemClickListener {

    @Bind(R.id.title_actor)
    TitleBar titleBar;
    @Bind(R.id.lv_actor)
    ListView lv_actor;
    @Bind(R.id.rl_actor_all)
    RelativeLayout rlAllActor;
    @Bind(R.id.rl_actor_age)
    RelativeLayout rlAgeActor;
    @Bind(R.id.sidrbar_actor)
    SideBar sideBar;
    @Bind(R.id.dialog)
    TextView dialog;
    @Bind(R.id.tv_actor_all)
    TextView tv_actor_all;
    @Bind(R.id.tv_actor_age)
    TextView tv_actor_age;
    //  根据拼音来排列ListView里面的数据类
    private PinyinComparator2 pinyinComparator;
    private List<ActorBean.YrlistBean> actorBeanList;
    private ActorAdapter adapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private PopupWindow sortPopAll;//排序-全部弹窗
    private PopupWindow ageSortPop;//排序-年龄弹窗
    private int page = 1;
    private int sign1 = 1;//性别条件（1全部 2男 3女）
    private int sign2 = 1;//年龄条件（1 全部 2 20岁以下 3 20-30 4 30-40 5 40岁以上）
    private UserInfoBean userInfoBean;

    @Override
    public int getContentViewLayout() {
        return R.layout.fragment_actor;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init() {
        initData();
        setListener();
    }

    private void setListener() {
        lv_actor.setOnItemClickListener(this);
        titleBar.setTopBarClickListener(this);
        sideBar.setTextView(dialog);
        //设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(this);
        rlAllActor.setOnClickListener(this);
        rlAgeActor.setOnClickListener(this);
    }

    private void initData() {
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        actorBeanList = new ArrayList<>();
        //根据拼音来排列ListView里面的数据类
        pinyinComparator = new PinyinComparator2();
//        actorBeanList = filledData(getResources().getStringArray(R.array.date));
        adapter = new ActorAdapter(ctx, actorBeanList);
        lv_actor.setAdapter(adapter);

    }

    @Override
    public void onResume() {
        super.onResume();
        userInfoBean = UserInfoBean.getInstance();
        actorBeanList.clear();
        requestYrList();
    }

    private void requestYrList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        HttpMethod.yrList(this, ctx, map, UrlConfig.HTTP_YR_LIST);
    }

    @Override
    public void onTouchingLetterChanged(String s) {
        // 该字母首次出现的位置
        int position = adapter.getPositionForSection(s.charAt(0));
        if (position != -1) {
            lv_actor.setSelection(position);
        }
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<ActorBean.YrlistBean> filledData(String[] date) {
        List<ActorBean.YrlistBean> mSortList = new ArrayList<ActorBean.YrlistBean>();

        for (int i = 0; i < date.length; i++) {
            ActorBean.YrlistBean sortModel = new ActorBean.YrlistBean();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();
            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_actor_all://全部
                if (sortPopAll != null && sortPopAll.isShowing()) {
                    sortPopAll.dismiss();
                } else {
                    showSortAllPop();
                }
                break;
            case R.id.rl_actor_age://年龄
                if (ageSortPop != null && ageSortPop.isShowing()) {
                    ageSortPop.dismiss();
                } else {
                    showAgeSortPop();
                }
                break;
            case R.id.tv_all_sort://全部艺人
                allActor();
                sortPopAll.dismiss();
                break;
            case R.id.tv_man_sort://男性艺人
                manActor();
                sortPopAll.dismiss();
                break;
            case R.id.tv_woman_sort://女性艺人
                womanActor();
                sortPopAll.dismiss();
                break;
            case R.id.tv_age_all://年龄（全部）
                tv_actor_age.setText("全部");
                sign2 = 1;
                requestSousuoYr();
                ageSortPop.dismiss();
                break;
            case R.id.tv_age_tab1://20岁以下
                tv_actor_age.setText("20岁以下");
                sign2 = 2;
                requestSousuoYr();
                ageSortPop.dismiss();
                break;
            case R.id.tv_age_tab2://20-30岁
                tv_actor_age.setText("20-30岁");
                sign2 = 3;
                requestSousuoYr();
                ageSortPop.dismiss();
                break;
            case R.id.tv_age_tab3://30-40岁
                tv_actor_age.setText("30-40岁");
                sign2 = 4;
                requestSousuoYr();
                ageSortPop.dismiss();
                break;
            case R.id.tv_age_tab4://40岁以上
                tv_actor_age.setText("40岁以上");
                sign2 = 5;
                requestSousuoYr();
                ageSortPop.dismiss();
                break;
            case R.id.blank_view:
                if (sortPopAll != null && sortPopAll.isShowing()) {
                    sortPopAll.dismiss();
                }
                if (ageSortPop != null && ageSortPop.isShowing()) {
                    ageSortPop.dismiss();
                }
                break;
        }
    }

    /*
    * 显示女性艺人
    * */
    private void womanActor() {
        tv_actor_all.setText("女");
        sign1 = 3;
        requestSousuoYr();
    }

    /*
  * 显示男性艺人
  * */
    private void manActor() {
        tv_actor_all.setText("男");
        sign1 = 2;
        requestSousuoYr();
    }

    /*
    * 显示全部艺人
    * */
    private void allActor() {
        tv_actor_all.setText("全部");
        sign1 = 1;
        requestSousuoYr();
    }

    private void requestSousuoYr() {
        HashMap<String, String> map = new HashMap<>();
        map.put("page", page + "");
        map.put("sign1", sign1 + "");
        map.put("sign2", sign2 + "");
        map.put("user_id", userInfoBean.getId());
        map.put("token", userInfoBean.getToken());
        HttpMethod.sousuoYr(this, ctx, map, UrlConfig.HTTP_SOUSUOYR);
    }

    /**
     * 显示排序pop
     */
    private void showSortAllPop() {
        Drawable drawable = getResources().getDrawable(R.drawable.icon_checx_on);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_actor_all.setCompoundDrawables(null, null, drawable, null);
        if (sortPopAll == null) {
            sortPopAll = new PopupWindow(ctx);
            sortPopAll.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            sortPopAll.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            sortPopAll.setBackgroundDrawable(getResources().getDrawable(R.color.tran));
            sortPopAll.setOutsideTouchable(true);
            sortPopAll.setFocusable(true);
            View sort_view = LayoutInflater.from(ctx).inflate(R.layout.popwindow_sort_layout_actor_all, null);
            TextView tvAll = (TextView) sort_view.findViewById(R.id.tv_all_sort);
            TextView tvMan = (TextView) sort_view.findViewById(R.id.tv_man_sort);
            TextView tvWoman = (TextView) sort_view.findViewById(R.id.tv_woman_sort);
            View view = sort_view.findViewById(R.id.blank_view);
            tvAll.setOnClickListener(this);
            tvMan.setOnClickListener(this);
            tvWoman.setOnClickListener(this);
            view.setOnClickListener(this);
            sortPopAll.setContentView(sort_view);
            sortPopAll.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tv_actor_all.setCompoundDrawables(null, null, drawable, null);
                }
            });
        }
        sortPopAll.showAsDropDown(rlAllActor);
    }

    /**
     * 显示年龄排序pop
     */
    private void showAgeSortPop() {
        Drawable drawable = getResources().getDrawable(R.drawable.icon_checx_on);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        tv_actor_age.setCompoundDrawables(null, null, drawable, null);
        if (ageSortPop == null) {
            ageSortPop = new PopupWindow(ctx);
            ageSortPop.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
            ageSortPop.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
            ageSortPop.setBackgroundDrawable(getResources().getDrawable(R.color.tran));
            ageSortPop.setOutsideTouchable(true);
            ageSortPop.setFocusable(true);
            View sort_view = LayoutInflater.from(ctx).inflate(R.layout.popwindow_sort_layout_actor_age, null);
            sort_view.findViewById(R.id.tv_age_all).setOnClickListener(this);
            sort_view.findViewById(R.id.tv_age_tab1).setOnClickListener(this);
            sort_view.findViewById(R.id.tv_age_tab2).setOnClickListener(this);
            sort_view.findViewById(R.id.tv_age_tab3).setOnClickListener(this);
            sort_view.findViewById(R.id.tv_age_tab4).setOnClickListener(this);
            sort_view.findViewById(R.id.blank_view).setOnClickListener(this);
            ageSortPop.setContentView(sort_view);
            ageSortPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Drawable drawable = getResources().getDrawable(R.drawable.icon_down);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    tv_actor_age.setCompoundDrawables(null, null, drawable, null);
                }
            });
        }
        ageSortPop.showAsDropDown(rlAllActor);
    }

    @Override
    public void rightClick() {
        super.rightClick();
        Intent intent = new Intent(ctx, ActorSearchResultActivity.class);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(ctx, ActorDetailsActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("YrList", actorBeanList.get(position));
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onSuccessHttp(String responseInfo, int resultCode) {
        super.onSuccessHttp(responseInfo, resultCode);
        switch (resultCode) {
            case UrlConfig.HTTP_YR_LIST:
                ActorBean actorBean = GsonUtil.GsonToBean(responseInfo, ActorBean.class);
                if (actorBean != null) {
                    List<ActorBean.YrlistBean> addList = actorBean.getYrlist();
                    if (addList != null && addList.size() > 0) {
                        for (int i = 0; i < addList.size(); i++) {
                            // 汉字转换成拼音
                            String pinyin = characterParser.getSelling(addList.get(i).getName());
                            String sortString = pinyin.substring(0, 1).toUpperCase();
                            // 正则表达式，判断首字母是否是英文字母
                            if (sortString.matches("[A-Z]")) {
                                addList.get(i).setSortLetters(sortString.toUpperCase());
                            } else {
                                addList.get(i).setSortLetters("#");
                            }
                        }
                        actorBeanList.addAll(addList);
                    }
                    adapter.notifyDataSetChanged();
                    // 根据a-z进行排序源数据
                    Collections.sort(actorBeanList, pinyinComparator);
                }
                break;
            case UrlConfig.HTTP_SOUSUOYR:
                ActorBean resultBean = GsonUtil.GsonToBean(responseInfo, ActorBean.class);
                if (resultBean != null) {
                    List<ActorBean.YrlistBean> addList = resultBean.getYrlist();
                    actorBeanList.clear();
                    if (addList != null && addList.size() > 0) {
                        for (int i = 0; i < addList.size(); i++) {
                            // 汉字转换成拼音
                            String pinyin = characterParser.getSelling(addList.get(i).getName());
                            String sortString = pinyin.substring(0, 1).toUpperCase();
                            // 正则表达式，判断首字母是否是英文字母
                            if (sortString.matches("[A-Z]")) {
                                addList.get(i).setSortLetters(sortString.toUpperCase());
                            } else {
                                addList.get(i).setSortLetters("#");
                            }
                        }
                        actorBeanList.addAll(addList);
                        // 根据a-z进行排序源数据
                        Collections.sort(actorBeanList, pinyinComparator);
                    } else {
                        ToastUtil.makeShortText(ctx, "没有符合条件的艺人");
                    }
                    adapter.notifyDataSetChanged();
                }
                break;
        }
    }
}
